#!/usr/bin/env python
# -*- coding: utf-8 -*-




# Needed to use Django as a standalone ORM
#######################################

import sys
import os
#trunkDir = os.getcwd()
# remove the last two dirs, equivalent to os.getcwd() + '/../../' but python doesn't like it
#trunkDir = trunkDir[ 0 : trunkDir[ 0 : trunkDir.rfind('/') ].rfind('/')+1 ]
#print trunkDir
trunkDir = '/var/www/'
sys.path.append(trunkDir)

# Import django project settings
from django.core.management import setup_environ
from rtve import settings

# avoid fk constrains when inserting
#settings.DATABASE_OPTIONS['init_command'] = 'SET FOREIGN_KEY_CHECKS = 0'
setup_environ(settings)

from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist

######################################




# General imports
from pyquery import PyQuery as pq
from datetime import datetime, date, timedelta
import urllib2

# Models imports
from rtve.core.models import Channel, Show, ShowTime





today = date.today()
one_day = timedelta(days=1)
tomorrow = today + one_day
aftertomorrow = tomorrow + one_day

urls = [
    (today,         'http://www.rtve.es/television/components/parrilla/mod_parrilla_tve_hoy.inc'),
    (tomorrow,      'http://www.rtve.es/television/components/parrilla/mod_parrilla_tve_manana.inc'),
    (aftertomorrow, 'http://www.rtve.es/television/components/parrilla/mod_parrilla_tve_pasado.inc')
]

def processShow(show, channel, dateP):
    p = pq(show)

    name = p('h3').text()

    hour = p('h3 span.hour').text()

    web = p('a[@title="web"]').attr.href
    if web: web.strip()

    info = p('a[@rel="facebox"]').attr.href
    if info: info.strip()
    info = urllib2.urlopen('http://www.rtve.es'+info).read().decode('iso-8859-1').encode('utf-8')
    
    if hour:
        hour = hour.strip()
        name = name[len(hour)+1:]
        hour = datetime.strptime(hour, '%H:%M')
        hour = datetime.combine( dateP, hour.timetz());
    
    if name:
        # Save show in DB
        (channel, newCh) = Channel.objects.get_or_create( name = channel )
        print (name, channel)
        (showObj, newSh) = Show.objects.get_or_create(name=name)
        if newSh:
            showObj.web = web
            showObj.info = info
            showObj.save()
#        try:
#            showObj.save()
#        except:
#            # Show already in DB
#            pass
    
        if hour:
            showTimeObj = ShowTime( show=showObj, datetime=hour, channel=channel) 
            showTimeObj.save()
 
    return (name,hour,web,info)



############################################
# Main
############################################

if __name__ == '__main__':
    for url in urls:
        print 'Processing: ' +url[0].__str__()
        p = pq( url[1] )

        # List of channels
        channels = p('div#channels li h2')
        listCh = []
        for channel in channels:
            ch =  pq(channel).text()
            listCh.append(ch)
#            chObj = Channel(name=ch)
#            try:
#                chObj.save()
#            except:
#                # Channel already in DB
#                pass
            print ch.encode('iso-8859-1')
            
        p2 = p('div#parrilla ul[@rel="tve"]')
        channel_id = 0
        for channel in p2:
            # List of shows per channel
            channel = pq(channel)
            shows = channel('li')
            for show in shows:
                print processShow(show, listCh[channel_id], url[0])
            channel_id += 1
